<template>
  <div class="app-container">
    <wise-crud ref="wise-crud" :urls="urls" :fields="fields" :handle="handle">
      <template slot="outHandle">
        <el-col :span="3">
          <el-button v-permission="['superSysOpsAdmin', 'entAdmin','proAdmin','formalEmployee']" type="primary"
            @click="handleAdd()">
            <i class="el-icon-plus" />
            发起
          </el-button>
        </el-col>
      </template>
      <template v-slot:handle="slotProps" label-width="500px">
        <!-- 1 通过 2 驳回   11 待公司审批 12 待集团审批 -->
        <el-button v-if="slotProps.row.initiateStatus === 1 && !slotProps.row.projectId" type="success" size="small"
          round @click.native.prevent="createProjectHandle(slotProps.row)">
          创建
        </el-button>
        <el-button v-if="slotProps.row.initiateStatus === 2" type="primary" size="small" round
          @click.native.prevent="editHandle(slotProps.row)">
          编辑
        </el-button>
        <el-button type="info" size="small" round @click.native.prevent="viewHandle(slotProps.row)">查看</el-button>
        <el-button v-if="slotProps.row.initiateStatus != 1" v-permission="['superSysOpsAdmin', 'entAdmin']"
          type="danger" size="small" round @click.native.prevent="removeHandle(slotProps.row)">
          删除
        </el-button>
      
      </template>
    </wise-crud>
    <!-- 添加/编辑 -->
    <el-dialog ref="drawer" :title="title" :visible.sync="drawer" destroy-on-close>
      <div v-if="drawer" class="draw-body">
        <div class="wise-form">
          <el-form ref="ruleForm" :model="object" :rules="rules" :validate-on-rule-change="false" label-width="130px"
            label-suffix=":">
            <el-form-item v-if="object.rejectReason" label="驳回原因" prop="rejectReason">
              {{ object.rejectReason }}
            </el-form-item>
            <el-form-item label="计划名称" prop="item_name">
              <el-input v-model="object.item_name" placeholder="请输入项目名称" clearable autofocus />
            </el-form-item>
            
            <el-form-item label="计划种类" prop="item_type">
            <el-radio-group v-model="object.item_type">
                <el-radio v-for="(problem, index) in problemData" :key="index" :label="problem.id"  v-model="object.item_type" >{{ problem.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="项目类型" prop="item_lx">
              <el-radio-group v-model="object.item_lx">
                <el-radio key="1" label="1" >投资</el-radio>
                <el-radio key="2" label="2">维修</el-radio>
              </el-radio-group>
            </el-form-item>
               <el-form-item label="属地负责单位" prop="item_dwfzdw"> 
                <el-input v-model="object.item_dwfzdw" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />  
              </el-form-item>
       
            <el-form-item label="动火作业内容" prop="item_dhzynr">
              <el-input v-model="object.item_dhzynr" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
            <el-form-item label="管线名称" prop="item_guanxian">
              <el-input v-model="object.item_guanxian" placeholder="请输入管线名称" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
            <el-form-item label="设计管径" prop="item_sjgj">
              <el-input v-model="object.item_sjgj" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
          
            <el-form-item label="计划作业时间" >
              <el-date-picker  v-model="object.item_jhzysj1" type="date" placeholder="选择日期"  value-format="yyyy-MM-dd" ></el-date-picker>到
              <el-date-picker  v-model="object.item_jhzysj2" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" ></el-date-picker>
            </el-form-item>
 
            <el-form-item label="作业时间" prop="item_jhzysj">
              <el-input v-model="object.item_jhzysj" placeholder="请输入作业时间" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
           
            <el-form-item label="计划施工队伍" prop="item_jhsgdw">
              <el-input v-model="object.item_jhsgdw" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
           
            
            <el-form-item label="工作量" prop="item_gzl">
              <el-input v-model="object.item_gzl" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
            <el-form-item label="作业位置" prop="item_weizhi">
              <el-input v-model="object.item_weizhi" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
         <el-form-item label="备注" prop="notes"> 
          <el-input v-model="object.notes" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />  
        </el-form-item>
         
            <el-button type="primary" @click="submitForm('ruleForm')" :disabled="isDisabled">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <!-- 查看项目 -->
    <el-dialog ref="viewDrawer" title="查看计划" :visible.sync="viewDrawer" destroy-on-close>
      <div v-if="viewDrawer" class="draw-body">
        <div class="wise-form">
          <el-form :validate-on-rule-change="false" label-width="130px" label-suffix=":">
            <el-form-item label="计划名称" prop="problemTypeName">  {{ object.item_name }} </el-form-item>
            <el-form-item label="属地负责单位" prop="problemTypeName">  {{ object.item_dwfzdw }} </el-form-item>
            <el-form-item label="项目种类" prop="problemTypeName">   
              {{initiateStatusHandle( object.item_type )}}
            </el-form-item>
          
            <el-form-item label="项目类型" prop="problemTypeName">  {{initiateStatusHandle1( object.item_lx )}} </el-form-item>
            <el-form-item label="动火作业内容" prop="problemTypeName">  {{ object.item_dhzynr }} </el-form-item>
            <el-form-item label="设计管径" prop="problemTypeName">  {{ object.item_sjgj }} </el-form-item>
            <el-form-item label="计划作业时间" prop="problemTypeName">  {{ object.item_jhzysj1 }} - {{ object.item_jhzysj2 }}</el-form-item>
            <el-form-item label="计划时间" prop="problemTypeName">  {{ object.item_jhzysj }}</el-form-item>
            <el-form-item label="计划施工队伍" prop="problemTypeName">  {{ object.item_jhsgdw }} </el-form-item>
            <el-form-item label="工作量" prop="problemTypeName">  {{ object.item_gzl }} </el-form-item>
            <el-form-item label="作业位置" prop="problemTypeName">  {{ object.item_weizhi }} </el-form-item>
            <!-- <el-form-item label="经纬度" prop="problemTypeName">  精度：{{ object.wz_jing }}纬度：{{object. wz_wei }}</el-form-item> -->
             
            <el-form-item label="创建人" prop="problemTypeName">  {{ object.cname }} </el-form-item>
            <!-- <el-form-item label="创建时间"  type="date"  value-format="yyyy-MM-dd HH:mm:ss" prop="ct">  {{ object.ct }} </el-form-item> -->
            <el-form-item label="审批状态" prop="problemTypeName"> 
              {{initiateStatusHandle2( object.sp )}}  
             </el-form-item>
            <el-form-item v-if="object.sp>0||object.sp<0" label="审批人" prop="problemTypeName">  {{ object.sprname }} </el-form-item>
            <el-form-item v-if="object.sp<0||object.sp<0" label="审批意见" prop="problemTypeName">  {{ object.spbz }} </el-form-item>
           
         
          </el-form>
        </div>
      </div>
    </el-dialog>
    <!-- 主题弹层 -->
    <el-dialog title="设置主题" :visible.sync="themeDrawer" width="30%">
      <el-form ref="form" :model="themeObj" label-width="80px">
        <el-form-item label="设置主题">
          <el-select v-model="themeObj.code" clearable placeholder="请选择主题">
            <el-option label="绿松石蓝(默认)" value="default" />
            <el-option label="粉绿主题" value="theme2" />
            <el-option label="天蓝主题" value="theme3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="setThemeHandle">确定</el-button>
          <el-button @click="themeDrawer = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 创建项目 -->
    <CreateProjectForm ref="createProjectForm" />
  </div>
</template>

<script>
  import WiseCrud from '@/components/Crud/wiseCrud'
  import WiseFile from '@/components/Crud/components/wiseFile'
  import {
    postHandle
  } from '@/api'
  import {
    setSpaceId
  } from '../../../../utils/auth'
  import {
    imgPath
  } from '@/filters'
  import CreateProjectForm from './CreateProjectForm.vue'

  export default {
    name: 'ProviderManage',
    components: {
      WiseCrud,
      WiseFile,
      CreateProjectForm
    },
    data() {
      return {
        urls: {
          list: '/api/v1/welder-sbtx-second/project-plan/list',
          add: '/api/v1/welder-sbtx-second/project-plan/ppAdd',
          show: '/api/v1/welder-sbtx-second/project-plan/show/',
          update: '/api/v1/welder-sbtx-second/project-plan/ppUpda',
          delete: '/api/v1/welder-sbtx-second/project-plan/remove/'
        },
        fields: [{
            label: '序号',
            type: 'index',
            use: ['table']
          },
          {
            label: '计划名',
            prop: 'item_name',
            type: 'textarea',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '管线名称',
            prop: 'item_guanxian',
            type: 'textarea',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '属地负责单位',
            prop: 'item_dwfzdw',
            type: 'textarea',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '计划时间',
            prop: 'item_jhzysj',
            type: 'textarea',
            use: ['table', 'add', 'view', 'edit', 'search']
          },{
            label: '审批状态',
            prop: 'manage',
            type: 'render',
            labelWidth: '130px',
            tableRender: (h, row, index) => {
              let value
              switch (row.sp) {
              case 0:
                value = '未审批'
                break
              case 1:
                value = '同意'
                break
              case -1:
                value = '不同意'
                break
              case 2:
                value = '已创建'
                break
              default:
                value = '类型错误'
            }
              return h('el-row',  value)
            },
           
            use: ['table', 'view']
          },

          {
            label: '所属企业',
            prop: 'item_dwfzdw',
            type: 'textarea',
            use: ['table', 'add', 'view', 'edit', ]
          },

          {
            label: '项目种类',
            prop: 'manage',
            type: 'render',
            labelWidth: '130px',
            tableRender: (h, row, index) => {
              let value
              switch (row.item_lx) {
              case '1':
                value = '投资'
                break
              case '2':
                value = '维修'
                break
             
              default:
                value = '类型错误'
            }
              return h('el-row',  value)
            },
           
            use: ['table', 'view']
          },
,
          {
            label: '动火作业内容',
            prop: 'item_dhzynr',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
          {
            label: '计划作业时间1',
            prop: 'item_jhzysj1',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
          {
            label: '计划施工队伍',
            prop: 'item_jhsgdw',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
          {
            label: '工作量',
            prop: 'item_gzl',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
          {
            label: '创建人',
            prop: 'cname',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
        
         
          {
            label: '作业位置',
            prop: 'item_weizhi',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
          {
            label: '经纬度',
            prop: 'wz_jing',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
          {
            label: '创建时间',
            prop: 'ct',
            type: 'handle',
            use: ['textarea'],
            handle: [ 'edit', 'view', 'delete'],
            tableWidth: 320
          } , {
            label: '审批状态',
            prop: 'sp',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          }, {
            label: '审批人',
            prop: 'spr',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          }, {
            label: '审批意见',
            prop: 'spbz',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },{
            label: '操作',
            type: 'handle',
            use: ['table'],
            handle: [ ],
            tableWidth: 320
          }
        ],
        value2: "",
        value1: "",
        handle: [],
        drawer: false,
        viewDrawer: false,
        themeDrawer: false,
        isDisabled: false,
        title: '发起项目',
        object: {
          problemTypeName: null,
          depict: null,
          approvalUserId: null,
          name: null,
          imageUrl: ''
        },
        nullUserId: null,
        isSubminBtn: false,
        rules: {
          item_name: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          item_type: [{
            required: true,
            message: '必选项不能为空',
            trigger: 'blur'
          }],
          item_lx: [{
            required: true,
            message: '必选项不能为空',
            trigger: 'blur'
          }],
          item_dhzynr: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          item_jhzysj: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          
          item_sjgj: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          item_gzl: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          item_weizhi: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          item_jhsgdw: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }] ,
          item_guanxian: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }] ,
          item_dwfzdw: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }] 
          
          
          
        },
        themeObj: {
          id: null,
          code: 'default'
        },
        problemData: [],
        approvalData: [],
        maxPageSize: {
          ps: 9999,
          p: 1
        }
      }
    },
    computed: {
      entSpaceId() {
        return this.$store.getters.entSpaceId
      }
      // filters() {
      //   if (this.$store.state.user.project) {
      //     return [
      //       {
      //         field: 'id',
      //         operator: 'EQUALS',
      //         value: this.$store.state.user.project.id
      //       }
      //     ]
      //   } else {
      //     return []
      //   }
      // }
    },

    created() {
      this.getApprovalData()
      this.getProblemData()
     
     
    },    mounted() {
        window.location.reload(true);
    },

    methods: {
      // 根据企业entSpaceId获取企业全部的管理员
      getApprovalData() {
        postHandle(`/api/v1/welder-uac-second/space-user-member-role-comb/get-ent-admin/${this.entSpaceId}`, {
          d: {
            page: this.maxPageSize
          }
        }).then(res => {
          this.approvalData = res.result
        })
      },
      // 问题选择
      getProblemData() {
        let params = {
          d: {
            filters: [{
              field: 'pdCode',
              operator: 'EQUALS',
              value: 'problem'
            }],
            page: this.maxPageSize,
            sorts: [{
              field: 'ct',
              isDesc: false
            }]
          }
        }
        postHandle('/api/v1/welder-sbtx-second/dictionary', params).then(res => {
          this.problemData = res.result
        })
      },
      // 发起状态审批
      initiateStatusHandle(state) {
        let value
        switch (state) {
          case 1:
            value = '通过'
            break
          case 2:
            value = '驳回'
            break
          case 11:
            value = '待公司审批'
            break
          case 12:
            value = '待集团审批'
            break
          default:
            value = '暂无数据'
        }
        return value
      },
      // 问题
      problemTypeHandle(code) {
        if (code) {
          let obj = this.problemData.find(item => item.code === code)
          if (obj) {
            return obj.name
          } else {
            return '暂无数据'
          }
        }
      },
      handleAdd() {
        this.title = '发起项目'
        this.object = {
          name: null
        }
        this.drawer = true
      },
      editHandle(row) {


        this.title = '编辑项目'
        this.object = {
          imageUrl: ''
        }
        this.fileList = []
        this.getObjectById(row.id)
        this.drawer = true
      },
      viewHandle(row) {
        this.getObjectById(row.id)
        this.viewDrawer = true
      },
      removeHandle(row) {
        this.$confirm('您确定要删除该项目, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.removeById(row.id)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      onChangeApprovalId(val) {
        if (val !== this.nullUserId) {
          this.isSubminBtn = false
        }
      },
      // 详情
      getObjectById(id) {
        postHandle(this.urls.show + id, {}).then(response => {
          this.object = response.result
          let data = response.result
          this.nullUserId = data.approvalUserId
          if (this.approvalData.findIndex(item => item.userId == data.approvalUserId) === -1) {
            this.isSubminBtn = true
            this.approvalData.push({
              userId: data.approvalUserId,
              username: "用户不存在",
              disabled: true
            })
          }
        })
      },
      // 删除
      removeById(id) {
        postHandle(this.urls.delete + id, {})
          .then(response => {
            this.$message('删除成功')
            this.themeDrawer = false
            this.$refs['wise-crud'].handleSearch(1)
          })
          .catch(error => {
            this.loading = false
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(data[key]))
            }
          })
      },
      // 提交
      submitForm(formName) {
        if (this.isSubminBtn) {
          this.$message('用户不存在')
          return false
        }
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.isDisabled = true
            let url
            let item_type1
            let obj = JSON.parse(JSON.stringify(this.object))
            if (this.object.item_type) {
              item_type1 = this.problemData.find(item => item.name === this.object.item_type)
            }
            if (this.object.id) {
              url = this.urls.update + this.object.id
            } else {
              url = this.urls.add
            }
             
            postHandle(url, {
                obj
              })
              .then(response => {
                this.$message('操作成功')
                this.drawer = false
                this.isDisabled = false
                if (this.object.id) {
                  this.$refs['wise-crud'].handleSearch(0)
                } else {
                  this.$refs['wise-crud'].handleSearch(1)
                }
              })
              .catch(error => {
                const data = error.response.data
                for (const key in data) {
                  this.$message.error(this.$t(key + '.' + data[key]))
                }
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 重置
      resetForm(formName) {
        this.object = {
          problemTypeName: null,
          depict: null,
          approvalUserId: null,
          name: null,
          imageUrl: ''
        }

        // this.$refs[formName].resetFields()
      },
      // 项目管理
      screenMonitor(row) {
    
          setSpaceId(row.spaceId)
          window.location.href = '/project'
       
      },
      // 设置主题
      setTheme(row) {
        // this.themeObj.id = row.id
        // this.themeObj.projectId = row.projectId
        this.themeObj.id = row.projectId
        this.themeObj.code = row.code ? row.code : 'default'
        this.themeDrawer = true
      },
      // 设置主题
      setThemeHandle() {
        postHandle(`/api/v1/welder-sbtx-second/project-info-comb/update-project-code/${this.themeObj.id}`, {
            d: {},
            obj: this.themeObj
          })
          .then(response => {
            this.$message('操作成功')
            this.themeDrawer = false
            this.$refs['wise-crud'].handleSearch(1)
          })
          .catch(error => {
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(key + '.' + data[key]))
            }
          })
      },  initiateStatusHandle(state) {
        let value
        switch (state) {
          case '632c38231768324e416ba907':
            value = '管体'
            break
          case '632c388c1768324e416ba908':
            value = '焊缝'
            break
          case '632c390f1768324e416ba909':
            value = '线改'
            break
          case '632c39361768324e416ba90a':
            value = '其他'
            break
          default:
            value = '类型错误'
        }
        return value
      }, initiateStatusHandle1(state) {
        let value
        switch (state) {
          case '1':
            value = '投资'
            break
          case '2':
            value = '维修'
            break
        
          default:
            value = '类型错误'
        }
        return value
      },initiateStatusHandle2(state) {
        let value
        switch (state) {
          case '0':
            value = '未审批'
            break
          case '1':
            value = '同意'
            break
          case '-1':
            value = '不同意'
            break
          default:
            value = '状态错误'
        }
        return value
      },
      getSrcList(str) {
        let arr = []
        if (str) {
          arr = str.split(';')
        }
        return arr.map(item => imgPath(item))
      } ,
 
      createProjectHandle({
        id,
        name
      }) {
        this.$refs['createProjectForm'].title = '创建项目'
        this.$refs['createProjectForm'].object.name = name
        this.$refs['createProjectForm'].initiateProjectId = id
        this.$refs['createProjectForm'].drawer = true
      }
}}
  
</script>

<style lang="less" scoped>
  .image {
    width: 150px;
    height: 150px;
    margin-right: 10px;
  }
</style>